package com.boot.weirdor.module.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.boot.weirdor.module.entity.Role;
import com.boot.weirdor.module.entity.UserRole;
import com.boot.weirdor.module.mapper.RoleMapper;
import com.boot.weirdor.module.mapper.RoleResourceMapper;
import com.boot.weirdor.module.mapper.UserRoleMapper;
import com.boot.weirdor.module.service.IRoleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.boot.weirdor.module.service.IUserRoleService;
import org.apache.commons.lang.StringUtils;
import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author weirdor
 * @since 2017-08-09
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {


    @Autowired
    private RoleMapper roleMapper;


    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleResourceMapper roleResourceMapper;

    @Autowired
    private IUserRoleService userRoleService;
    /**
     * 根据用户查询
     * */
    public Map<String, Set<String>> selectResourceMapByUserId(Long id) {
        Map<String,Set<String>> resourceMap=new HashMap<String, Set<String>>();
        List<Long> roleIdList=userRoleMapper.selectRoleIdListByUserId(id);
        Set<String> urlSet = new HashSet<String>();
        Set<String> roles = new HashSet<String>();
        for (Long roleId : roleIdList) {
            List<Map<Long, String>> resourceList = roleMapper.selectResourceListByRoleId(roleId);
            if (resourceList != null) {
                for (Map<Long, String> map : resourceList) {
                    if (StringUtils.isNotBlank(map.get("url"))) {
                        urlSet.add(map.get("url"));
                    }
                }
            }
            Role role = roleMapper.selectById(roleId);
            if (role != null) {
                roles.add(role.getName());
            }
        }
        resourceMap.put("urls", urlSet);
        resourceMap.put("roles", roles);
        return resourceMap;
    }

    /**
     * 查询所有角色
     *
     * @return
     */
    public List<Role> selectAll() {
        EntityWrapper<Role> wrapper = new EntityWrapper<Role>();
        //根据排序号进行排序
        wrapper.orderBy("seq");
        return roleMapper.selectList(wrapper);
    }

    /**
     * 根据角色id查询资源
     */
    public List<Long> selectResourceIdListByRoleId(Long id) {
        return roleMapper.selectResourceIdListByRoleId(id);
    }


}
